package com.app.utils.base.j2se;

import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class ExcelUtil {
	public static void main(String[] args) throws IOException {
		//
		ExcelUtil xlsMain = new ExcelUtil();
		List<List<Object>> lists=xlsMain.readXls("D:/equip_arms.xlsx");
		List<Object> titles=lists.get(0);
		for (int i = 1; i < lists.size(); i++) {
			List<Object> values=lists.get(i);
			JSONObject jsonObject=new JSONObject();
			for (int j = 0; j < titles.size(); j++) {
				if (j>values.size()-1) {
					jsonObject.put(titles.get(j), null);
				}else {
					jsonObject.put(titles.get(j), values.get(j));
				}
			}
//			EquipArms arms=(EquipArms) JSONObject.toBean(jsonObject, EquipArms.class);
			System.out.println("");
		}
		System.out.println(lists.size());
    }
 
    /**
     * 读取xls文件内容
     * 
     * @return List<XlsDto>对象
     * @throws IOException
     *             输入/输出(i/o)异常
     */
    public List<List<Object>> readXls(String path) throws IOException {
        InputStream is = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        List<List<Object>> list = new ArrayList<List<Object>>();
        // 循环工作表Sheet
        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
        if (hssfSheet == null) {
        	return list;
        }
        // 循环行Row
        for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
            HSSFRow hssfRow = hssfSheet.getRow(rowNum);
            if (hssfRow == null) {
                continue;
            }
            List<Object> cells=new ArrayList<Object>();
            for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
            	HSSFCell cell = hssfRow.getCell(cellNum);
                if (cell == null) {
                	cells.add("");
                }else {
                	cells.add(getValue(cell));
				}
                
			}
            list.add(cells);
        }
        return list;
    }
 
    /**
     * 得到Excel表中的值
     * 
     * @param hssfCell
     *            Excel中的每一个格子
     * @return Excel中每一个格子中的值
     */
    @SuppressWarnings("static-access")
    private Object getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return hssfCell.getBooleanCellValue();
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return (int)hssfCell.getNumericCellValue();
        }else if (hssfCell.getCellType()==HSSFCell.CELL_TYPE_BLANK) {
			return "";
		}else {
            // 返回字符串类型的值
            return hssfCell.getStringCellValue();
        }
    }
 
}
